package com.apache.database.constant;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import com.apache.cache.CacheManager;
import com.apache.cache.impl.LoadCacheFactory;

/**
 * description: 系统工具类
 * 
 */
public class SystemTools {

	private static SystemTools instance;

	private Map<String, CacheManager> cachePool = new HashMap<String, CacheManager>();//缓存池

	private long lastUpateTime = 0l;//最后修改时间

	private Map<String, String> constant = new HashMap<String, String>();//存放系统配置参数

	private String filePath = "";

	private SystemTools() {
		filePath = Validator.getClassLoaderPath() + "config/";
	}

	/**
	  * description: 启用单例模式
	  * @return
	 */
	public synchronized static SystemTools getInstance() {
		if (null == instance) {
			instance = new SystemTools();
		}
		return instance;
	}

	/**
	  * description: 获取缓存对象
	  * @param spaceName 缓存空间名
	  * @return
	 */
	public CacheManager getCache(String spaceName) {
		if (Validator.isEmpty(cachePool.get(spaceName))) {
			cachePool.put(spaceName, LoadCacheFactory.getInstance().getCacheManager(spaceName));
		}
		return cachePool.get(spaceName);
	}

	/**
	  * description: 加载配置文件
	 */
	private String initConfig(String key) {
		File oldfile = new File(filePath + "unity_config.properties");
		long lastModletime = oldfile.lastModified();
		if (lastUpateTime < lastModletime) {//有更新从新加载
			lastUpateTime = lastModletime;
			Properties prop = Validator.getProperties(filePath + "unity_config.properties");
			Map<String, String> map = new HashMap<String, String>((Map) prop);
			Set propertySet = map.entrySet();
			for (Object o : propertySet) {
				Map.Entry entry = (Map.Entry) o;
				constant.put(entry.getKey().toString(), entry.getValue().toString());
			}
		}
		if (Validator.isNull(key))
			return "";
		else
			return Validator.getDefaultStr(constant.get(key), "");
	}

	/**
	  * description: 获取所有配置信息
	  * @return
	 */
	public Map<String, String> getMap() {
		initConfig("");
		return constant;
	}

	/**
	  * description: 根据指定的KEY获取相应配置信息
	  * @param key   指定的KEY
	  * @return
	 */
	public String getValue(String key) {
		return initConfig(key);
	}

	public String getValue(String key, String charset) {
		try {
			charset = Validator.getDefaultStr(charset, "UTF-8");
			String result = new String(initConfig(key).getBytes("iso8859-1"), charset);
			return result;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "";
	}
}
